// stores/auth.js
import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { request } from '@/api/request'

let refreshPromise = null // 全局缓存刷新请求，避免并发重复刷新

export const useAuthStore = defineStore('auth', () => {
    const token = ref(localStorage.getItem('token') || null)
    const tokenExpireTime = ref(localStorage.getItem('tokenExpireTime') || null)
    const loading = ref(false)
    const error = ref(null)

    // 判断 token 是否有效
    const isTokenValid = computed(() => {
        if (!token.value || !tokenExpireTime.value) return false
        return Date.now() < parseInt(tokenExpireTime.value)
    })

    // 刷新 token（真正发请求）
    async function fetchToken() {
        if (isTokenValid.value) {
            return token.value
        }
        loading.value = true
        error.value = null
        try {
            const response = await request({
                url: '/auth',
                method: 'post'
            })
            const authHeader = response.headers['authorization']
            if (authHeader) {
                const newToken = authHeader.replace(/^Bearer\s+/i, '')
                setToken(newToken)
                return newToken
            } else {
                throw new Error('未获取到 Authorization 头')
            }
        } catch (err) {
            error.value = err.response?.data?.message || err.message
            throw err
        } finally {
            loading.value = false
        }
    }

    // 包装一层，保证并发时只会触发一次刷新
    async function fetchTokenOnce() {
        if (!refreshPromise) {
            refreshPromise = fetchToken().finally(() => {
                refreshPromise = null
            })
        }
        return refreshPromise
    }

    function setToken(newToken) {
        token.value = newToken
        localStorage.setItem('token', newToken)

        // 设置 700 分钟后过期
        const expireTime = Date.now() + 700 * 60 * 1000
        tokenExpireTime.value = expireTime
        localStorage.setItem('tokenExpireTime', expireTime.toString())
    }

    function clearToken() {
        token.value = null
        tokenExpireTime.value = null
        localStorage.removeItem('token')
        localStorage.removeItem('tokenExpireTime')
    }

    async function checkAndRefreshToken() {
        if (!isTokenValid.value) {
            clearToken()
            return await fetchTokenOnce()
        }
        return token.value
    }

    return {
        token,
        loading,
        error,
        isTokenValid,
        fetchToken,
        fetchTokenOnce,
        setToken,
        clearToken,
        checkAndRefreshToken
    }
})
